package com.gx.telephonedemo2;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;

/**
 * 录音的 Service
 * <p>
 * Created by developerHaoz on 2017/8/12.
 */

public class RecordingService extends Service {

    private static final String LOG_TAG = "RecordingService";

    private String mFileName = null;
    private String mFilePath = null;

    private MediaRecorder mRecorder = null;

    private long mStartingTimeMillis = 0;
    private long mElapsedMillis = 0;
    private TimerTask mIncrementTimerTask = null;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(1, initNotification());
        startRecording();
        return START_STICKY;
    }

    private Notification initNotification() {
        String channelID = "1";

        String channelName = "channel_name";
        NotificationCompat.Builder mBuild;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_DEFAULT);
            // 设置通知出现时不震动
            channel.enableVibration(false);
            channel.enableLights(false);
            channel.setVibrationPattern(new long[]{0});
            mNotificationManager.createNotificationChannel(channel);
            mBuild = new NotificationCompat.Builder(this, channelID);//该处写的应该是当前的channelId。
        } else {
            mBuild = new NotificationCompat.Builder(this);
        }
        mBuild.setContentTitle("正在录音...") //设置通知标题
                .setSmallIcon(R.mipmap.ic_launcher)
                .setDefaults(Notification.DEFAULT_LIGHTS) //设置通知的提醒方式： 默认
                .setPriority(NotificationCompat.PRIORITY_DEFAULT) //设置通知的优先级：最大
                .setAutoCancel(true)//设置通知被点击一次是否自动取消
//                .setContentText("下载进度:" + "0%")
//                .setProgress(100, 0, false)
                .setChannelId(channelID)
                .setOngoing(true);//设置不可清除模式
        return mBuild.build();//构建通知对象
    }

    @Override
    public void onDestroy() {
        Log.d(LOG_TAG, "录音服务停止。。");
        stopForeground(true);// 停止前台服务--参数：表示是否移除之前的通知
        if (mRecorder != null) {
            stopRecording();
        }
        super.onDestroy();
    }

    public void startRecording() {
        setFileNameAndPath();

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mRecorder.setOutputFile(mFilePath);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        mRecorder.setAudioChannels(1);
        mRecorder.setAudioSamplingRate(44100);
        mRecorder.setAudioEncodingBitRate(192000);

        try {
            mRecorder.prepare();
            mRecorder.start();
            mStartingTimeMillis = System.currentTimeMillis();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    }

    public void setFileNameAndPath() {
        int count = 0;
        File f;

        do {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
            Date curDate = new Date(System.currentTimeMillis());
            count++;
//            mFileName = getString(R.string.default_file_name)
//                    + "_" + (System.currentTimeMillis()) + ".mp4";
            mFileName = Constant.number + "_" + formatter.format(curDate) + ".mp4";
            mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath();
            mFilePath += "/CallAutoRecord/" + mFileName;
            f = new File(mFilePath);
        } while (f.exists() && !f.isDirectory());
    }

    public void stopRecording() {
        mRecorder.stop();
        mElapsedMillis = (System.currentTimeMillis() - mStartingTimeMillis);
        mRecorder.release();

        getSharedPreferences("sp_name_audio", MODE_PRIVATE)
                .edit()
                .putString("audio_path", mFilePath)
                .putLong("elpased", mElapsedMillis)
                .apply();
        if (mIncrementTimerTask != null) {
            mIncrementTimerTask.cancel();
            mIncrementTimerTask = null;
        }

        mRecorder = null;
    }

}
